package com.crx.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crx.springbootinit.mapper.ChatMapper;
import com.crx.springbootinit.model.dto.chat.ChatHistoryDTO;
import com.crx.springbootinit.model.dto.chat.ChatMarkReadDTO;
import com.crx.springbootinit.model.dto.chat.ChatPageDTO;
import com.crx.springbootinit.model.dto.page.PageVO;
import com.crx.springbootinit.model.entity.Chat;
import com.crx.springbootinit.model.entity.User;
import com.crx.springbootinit.model.vo.chat.ChatListVO;
import com.crx.springbootinit.model.vo.chat.ChatUserVO;
import com.crx.springbootinit.model.vo.chat.ChatVO;
import com.crx.springbootinit.model.vo.chat.Chatted;
import com.crx.springbootinit.service.IChatService;
import com.crx.springbootinit.service.IFollowService;
import com.crx.springbootinit.service.IUserService;
import com.crx.springbootinit.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 聊天消息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-21
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements IChatService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IFollowService followService;

    @Override
    public void markAsRead(ChatMarkReadDTO chatMarkReadDTO) {
        lambdaUpdate()
                .eq(Chat::getUserId,chatMarkReadDTO.getUserId())
                .eq(Chat::getTargetId,chatMarkReadDTO.getTargetId())
                .eq(Chat::getIsRead, false)
                .set(Chat::getIsRead, true).update();

    }

    @Override
    public PageVO<ChatVO> queryChatPage(ChatPageDTO chatPageDTO) {
        Integer pageSize = chatPageDTO.getPageSize();
        Integer pageNo = chatPageDTO.getPageNo();
        Page<ChatVO> page = new Page<>(pageNo, pageSize);
        IPage<ChatVO> chatVOIPage = baseMapper.queryChatPage(page, chatPageDTO);
        PageVO<ChatVO> pageVO=new PageVO<>();
        pageVO.setList(chatVOIPage.getRecords());
        pageVO.setTotal(chatVOIPage.getTotal());
        pageVO.setPages(chatVOIPage.getPages());
        return pageVO;
    }

    @Override
    public PageVO<Chatted> getChattedList(int pageNum, int pageSize) {
        Long userId = ThreadLocalUtil.get("userId");
        int offset = (pageNum - 1) * pageSize;
        List<Chat> chats = baseMapper.selectChattedList(userId, pageSize, offset);
        List<Chatted> chattedList = new ArrayList<>();
        for (Chat chat : chats) {
            Chatted chatted = new Chatted();
            BeanUtils.copyProperties(chat,chatted);
            Long otherUserId = chat.getUserId().equals(userId) ? chat.getTargetId() : chat.getUserId();
            chatted.setIsRead(chat.getUserId().equals(userId) ? true : chat.getIsRead());
            User otherUser = userService.getById(otherUserId);
            chatted.setCreateTime(chat.getCreateTime().format(DateTimeFormatter.ofPattern("MM-dd")));
            chatted.setUserId(otherUserId);
            chatted.setNickname(otherUser.getNickname());
            chatted.setAvatar(otherUser.getAvatar());
            chattedList.add(chatted);
        }
        // 获取总记录数以计算分页总数
        Long totalRecords = baseMapper.countChattedList(userId);
        Long totalPages = (totalRecords + pageSize - 1) / pageSize;  // 计算总页数

        return new PageVO<>(totalRecords,totalPages , chattedList);
    }

    /**
     * 前台聊天记录
     * @param chatHistoryDTO
     * @return
     */
    @Override
    public ChatUserVO getHistory(ChatHistoryDTO chatHistoryDTO) {
        ChatUserVO chatUserVO = new ChatUserVO();
        Long userId = ThreadLocalUtil.get("userId");
        User user = userService.getById(userId);
        User targetUser = userService.getById(chatHistoryDTO.getTargetId());
        chatUserVO.setNickname(targetUser.getNickname());
        chatUserVO.setAvatar(targetUser.getAvatar());
        chatUserVO.setMyAvatar(user.getAvatar());
        chatUserVO.setIsFollow(followService.isFollow(userId, targetUser.getId()));
        int page = chatHistoryDTO.getPageNo();  // 当前页
        int pageSize = chatHistoryDTO.getPageSize();  // 每页显示条数
        int offset = (page - 1) * pageSize;  // 计算偏移量
        List<ChatListVO> historyChatList = baseMapper.getHistoryChatList(userId, chatHistoryDTO.getTargetId(), pageSize, offset);
        Collections.reverse(historyChatList);
        chatUserVO.setChatListVO(historyChatList);
        markAsRead(new ChatMarkReadDTO(chatHistoryDTO.getTargetId(),userId));
        return chatUserVO;
    }
}
